"""API数据模型定义 - 定义请求和响应的数据结构。"""

import uuid
import time
import json
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field

# 定义消息类，用于封装API接口返回数据
class Message(BaseModel):
    role: str
    content: str

# 定义ChatCompletionRequest类
class ChatCompletionRequest(BaseModel):
    messages: List[Message]
    stream: Optional[bool] = False
    userId: Optional[str] = None
    conversationId: Optional[str] = None

# 定义ChatCompletionResponseChoice类
class ChatCompletionResponseChoice(BaseModel):
    index: int
    message: Message
    finish_reason: Optional[str] = None

# 定义ChatCompletionResponse类
class ChatCompletionResponse(BaseModel):
    id: str = Field(default_factory=lambda: f"chatcmpl-{uuid.uuid4().hex}")
    object: str = "chat.completion"
    created: int = Field(default_factory=lambda: int(time.time()))
    choices: List[ChatCompletionResponseChoice]
    system_fingerprint: Optional[str] = None

# 优化后的流式响应模型（参考参考文件的结构）
class StreamDelta(BaseModel):
    """流式响应中的增量内容。"""
    content: Optional[str] = None
    role: Optional[str] = None

class StreamChoice(BaseModel):
    """流式响应中的选择项。"""
    index: int
    delta: StreamDelta
    finish_reason: Optional[str] = None

class StreamResponse(BaseModel):
    """流式响应专用的数据块。"""
    id: str = Field(default_factory=lambda: f"chatcmpl-{uuid.uuid4().hex}")
    object: str = "chat.completion.chunk"
    created: int = Field(default_factory=lambda: int(time.time()))
    choices: List[StreamChoice]
    model: Optional[str] = None  # 添加模型字段
    system_fingerprint: Optional[str] = None  # 添加系统指纹






class ChatCompletionChunkChoice(BaseModel):
    """流式响应选项模型"""
    index: int
    delta: StreamDelta
    finish_reason: Optional[str] = None

class ChatCompletionChunkResponse(BaseModel):
    """流式响应模型"""
    id: str
    object: str
    created: int
    choices: List[ChatCompletionChunkChoice]

class SqlQueryRequest(BaseModel):
    """SQL查询请求类。"""
    query: str = Field(..., description="用户的SQL查询请求或数据库相关问题")
    userId: Optional[str] = None
    conversationId: Optional[str] = None
    database_uri: Optional[str] = "sqlite:///Chinook.db"

class SqlQueryResponse(BaseModel):
    """SQL查询响应类。"""
    id: str = Field(default_factory=lambda: f"sql-{uuid.uuid4().hex}")
    result: str
    success: bool = True
    error: Optional[str] = None
    created: int = Field(default_factory=lambda: int(time.time()))


# 线程相关模型
class ThreadInfo(BaseModel):
    """线程信息模型"""
    thread_id: str
    created_at: str
    updated_at: str
    metadata: Optional[Dict[str, Any]] = None
    message_count: Optional[int] = 0
    last_message: Optional[str] = None
    messages: Optional[List[Message]] = []  # 新增：完整的消息历史

class ThreadListResponse(BaseModel):
    """线程列表响应模型"""
    threads: List[ThreadInfo]
    total: int
    success: bool = True

class ThreadRequest(BaseModel):
    """线程请求模型"""
    userId: Optional[str] = None
    limit: Optional[int] = 100
    offset: Optional[int] = 0


# 登录相关模型
class LoginRequest(BaseModel):
    """登录请求模型"""
    username: str = Field(..., description="用户名")
    password: str = Field(..., description="密码")

class LoginResponse(BaseModel):
    """登录响应模型"""
    success: bool
    message: str
    userId: Optional[str] = None
    token: Optional[str] = None
    created: int = Field(default_factory=lambda: int(time.time()))

class UserInfo(BaseModel):
    """用户信息模型"""
    userId: str
    username: str
    created_at: str
    last_login: Optional[str] = None

class ValidateTokenRequest(BaseModel):
    """验证token请求模型"""
    token: str = Field(..., description="用户token")

class ValidateTokenResponse(BaseModel):
    """验证token响应模型"""
    valid: bool
    userId: Optional[str] = None
    message: str